package sajat.onlab;

import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

public class AsyncTaskRGeocode extends AsyncTask<String, Void, String[]> {

	public interface RGeocodeCompleteListener {
		   public void onTaskCompleteRG(String[] aText);
		   public void onErrorRG(String aError);
	}
	
	private Context context = null;
	private RGeocodeCompleteListener listener;
	private String error = null;

	public AsyncTaskRGeocode(Context context, RGeocodeCompleteListener aListener)
	{
	    this.context = context; 
	    listener = aListener;
	}
	
	@Override
	protected void onPreExecute() 
	{
		
	}
	
	@Override
	protected String[] doInBackground(String... params) {
		String[] result = null;
		try {
			URL url = new URL(params[0]);
	        
	      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	      DocumentBuilder db = dbf.newDocumentBuilder();
	      Document doc = db.parse(new InputSource(url.openStream()));
	      doc.getDocumentElement().normalize();
	      
	      NodeList address = doc.getElementsByTagName("formatted_address");
	      
	      result = new String[1];
	                          
	      result[0] = address.item(0).getTextContent();
		}
	    catch (Exception e) {
	    	error = e.getMessage();
	    	e.printStackTrace();
	    }
		return result;
	}
	

	protected void onPostExecute(String[] datas) 
	{
	    
	    if (error != null) {
	    	listener.onErrorRG(error);
	    }
	    else {
	    	listener.onTaskCompleteRG(datas);
	    }
	} 
}


